/**
 * session list呈现. 
 */
var sessionList = (function(){    
    var userGroupProfileTmp = [
        '<div>',
            '<figure class="suserProfile">',
                '<div class="suserProfileImg">',
                    '<img src="<%=o.icon || "/ujs/app/im/images/index/link.png" %>" />',
                '</div>',
                '<div class="suserProfileSummary">',                                                    
                    '<div class="suserPItem">',
                        '<label>Name</label>',
                        '<span><%=o.name%></span>',
                    '</div>',
                    '<div class="suserPItem">',
                        '<label>Creator</label>',
                        '<span><%=page.urlStore.getItem(o.sid || o.id).creator.name %></span>',
                    '</div>',
                    '<div class="suserPItem">',
                        '<label>Link</label>',
                        '<span title="<%=page.urlStore.getItem(o.sid || o.id).url %>">',
                            '<input readonly style="background: #FFF;width: 250px;text-indent: 1px;" value="<%=page.urlStore.getItem(o.sid  || o.id).url %>" />',
                        '</span>',
                    '</div>',
                    '<button style="bottom: 10px;position: absolute;right: 90px;letter-spacing: 1px;<%=o.perm && !o.perm.upd ? "display:none" : "" %>" class="suserChat edit" sid = "<%=o.sid  || o.id%>" >Edit</button>',
                    '<button style="bottom: 10px;position: absolute;right: 10px;letter-spacing: 1px;" class="suserChat" onclick=window.open("<%=page.urlStore.getItem(o.sid  || o.id).url%>")>Open</button>',
                '</div>',
            '</figure>',
        '</div>'
    ];        
    return Observable.create({
        /**
         * 初始化session list控件. 
         * @param {jQuery} $wrapper
         */
        init : function($wrapper){
            var _this = this;
            this.$wrapper = $wrapper;
            this.store = new Store('sid', SessionListDataAdapter);
            this.store.on('addItem', function(item){    
                var $newItem = $(tmpl(ChatPanelView.sessionItem, item)); 
                
                var unreadCount = $newItem.find('.unreadMsgCount').text(); 
                if(unreadCount > 0){
                    $newItem.addClass('blink');
                }         
                _this.addOrderly($newItem);                
                page.setUnread.defer(500, page);
                if(item.type == 'web'){                    
                    //lan.parse($item);
                    $newItem.tooltipster({                        
                        interactive : true,                          
                        position : 'right',
                        trigger : 'click',
                        theme : 'tooltipster-light',
                        content: 'Loading...',
                        contentAsHTML : true,
                        functionBefore: function(origin, continueTooltip) {                            
                            continueTooltip();
                            
                            var $item = $(tmpl(userGroupProfileTmp, page.urlStore.getItem(item.sid ) ));
                            $item.delegate('button.edit', 'click', function(){
                                var sid = $(this).attr('sid');                        
                                ujs.ui.Dialog.get(ShareURLDialog, { 
                                    title : lan("app.im.link.edit"), 
                                    mode : "edit", 
                                    relType : "web", 
                                    ueid : sid 
                                });
                                return false;
                            });
                            
                            //if (origin.data('ajax') !== 'cached') {  
                                var $tip = $item;
                                lan.parse($tip);                                  
                                origin.tooltipster('content', $tip).data('ajax', 'cached');                                                                            
//                            }
                        }
                    });
                }
            });
            
            this.store.on('updateItem', function(item){
                var $sessionItem = _this.$wrapper.find('.sessionListItem[sid={0}]'.format(item.sid)),
                    $newSessionItem = $(tmpl(ChatPanelView.sessionItem, item));
                
                if( $sessionItem.length ){                    
                    var isCurrentItem = false;
                    if($sessionItem.hasClass('current')){
                        isCurrentItem = true;
                    }
                    $sessionItem.replaceWith($newSessionItem);                    
                    //若未读数大于0, 则blink.
                    var unreadCount = $newSessionItem.find('.unreadMsgCount').text(); 
                    if(unreadCount > 0){
                        $newSessionItem.addClass('blink');
                    }
                    if(isCurrentItem){
                        $newSessionItem.addClass('current');
                    }                    
                } else {
                    _this.addOrderly($newSessionItem);
                    
                    var unreadCount = $newSessionItem.find('.unreadMsgCount').text(); 
                    if(unreadCount > 0){
                        $newSessionItem.addClass('blink');
                    }
                }                
                //page.setUnread.defer(500, page);
                window.setTimeout(function(){
                    page.setUnread(undefined, false);
                }, 500);
            });
            
            page.chatGroupStore.on('updateItem', function(chatGroupEntity){
                var $item = _this.getSessionItem(chatGroupEntity['id']);
                if($item.length){
                    _this.updateItem(chatGroupEntity['id']);
                }
            });
            /**
             * 点击关闭session
             */
            this.$wrapper.delegate('.sessionListCloseBtn', 'click', function(){
                
                var $sessionListItem = $(this).closest('.sessionListItem');
                var type = $sessionListItem.attr('type');
                var doneFun = function(){
                    if($sessionListItem.hasClass('current')){
                        page.contentCardLayout.showItem('dashboard');
                    }
                    $sessionListItem.remove();    
                };                
                if(['adminchat', 'singlechat', 'destruct', 'locationalert', 'event'].contains(type)){
                    var teid = $sessionListItem.attr('sid');
                    var chatGroupEntity = page.chatGroupStore.getItem(teid);
                    var confirmText = lan('app.im.chat.delTip');
                    if(chatGroupEntity.perm && chatGroupEntity.perm.del == '3'){
                        confirmText = lan('app.im.chat.delAdminChatTip');
                    }
                    bubble.confirm(confirmText.format(chatGroupEntity['name']), function(){
                        page.biz.exitChatGroup(teid, function(msg){
                            doneFun();
                        }); 
                    });
                } else {
                    var ueid = $sessionListItem.attr('sid');
                    var urlEntity = page.urlStore.getItem(ueid);                    
                    bubble.confirm('Delete {0}?'.format(urlEntity.name), function(){
                        page.biz.deleteLink(ueid, function(msg){
                            doneFun();    
                        }); 
                    }); 
                }
                return false;
            });
            /**
             * 点击session list item时. 
             */
            this.$wrapper.delegate('.sessionListItem', 'click', function(){
                var _item = this;
                var sid = $(this).attr('sid'),
                    type = $(this).attr('type');
                        

                
                $('button.h').trigger('click');                
                if(type == 'web'){                    
                    return;
                }                
                $(this).addExclusiveClass('current');
                
                var top2 = $(this).position().top;
                var height = $('#groupSessionList').height();
                
                if(top2 <= 0){
                    $('#groupSessionList').scrollTop(0);
                } else {
                    if(top2 >= height){
                        $('#groupSessionList').scrollTop(top2 + $('#groupSessionList').scrollTop() - 37);
                    }
                }                
                var isFirstOpen = false,
                    sessionData = sessionList.store.getItem(sid),
                    currentSeq = sessionData['currentSeq'],
                    latestSeq = sessionData['latestSeq'], 
                    minMsgCount = 30,
                    chatGroupEntity = page.chatGroupStore.getItem(sid) || { perm:{} },
                    isDestructChat = ChatGroupPerm.check(chatGroupEntity['perm'], ChatGroupPerm.DESTRUCTMESSAGE);
                                
                var chatPanel = page.contentCardLayout.getItem(sid);                 
                if(!chatPanel) {
                    isFirstOpen = true;
                    chatPanel = new ChatPanel(chatGroupEntity);                    
                    page.contentCardLayout.addItem(sid, chatPanel);
                } else {
                    if(chatPanel.hideParticipants){
                        chatPanel.hideParticipants();
                    }
                }
                page.contentCardLayout.showItem(sid);
                
                var trueCurrentSeq = 0;
                if(chatPanel.chatView){
                    trueCurrentSeq = chatPanel.chatView.getLastSeq();
                }
                if(trueCurrentSeq > 0){
                    currentSeq = trueCurrentSeq;
                }                
                unread = latestSeq - currentSeq;
                
                //加载未读.                
                var loadMsgCount = Math.min(latestSeq, minMsgCount);
                if(unread > minMsgCount){
                    loadMsgCount = Math.min(unread, 50);
                }
                 
                if(!isFirstOpen){
                    if(unread > 0){
                        loadMsgCount = unread;
                    } else { 
                        loadMsgCount = 0;
                    }
                }                
                if(isDestructChat){
                    loadMsgCount = unread;
                }  
                
                if(loadMsgCount > 0){
                    chatPanel.showMask();
                    
                    page.biz.getMsgListAsRead(sid, sessionData['latestSeq'], loadMsgCount)
                    .done(function(msg){
                        
                        
                        
                        if(isFirstOpen && !isDestructChat){
                            chatPanel.chatView.showLoadMore(msg['topics'].length);
                        }                                                
                        chatPanel.chatView.addTopic(msg['topics'].reverse());
                        
                        (function(){
                            chatPanel.chatView.refreshReadCount();
                        }).defer(0);
                                                                      
                        _this.updateItem(sid, function(teObj){
                            if(teObj && teObj['latestSeq']){
                                teObj['currentSeq'] = teObj['latestSeq'];
                            }
                            page.setUnread.defer(500, page);    
                        });                                     
                        if(chatGroupEntity.type === 'singlechat'){
                            page.biz.signMsgAsReaded(sid, sessionData['latestSeq'], function(msg){});
                            page.biz.getParticipantReadSeq(chatGroupEntity['te'], function(seq){
                               chatPanel.chatView.setMsgReaded(seq);
                            });
                        }
                        ujs.browser.WebNotification.hide(sid);
                        
                        $(_item).removeClass('blink');
                    })
                    .always(function(){
                        //关闭相关的notification.
                        chatPanel.hideMask();
                    });
                }
            });    
        },
        /**
         * 清除选中. 
         */
        clearSelection : function(){
            this.$wrapper.find('.sessionListItem.current').removeClass('current'); 
        },
        getCurrent : function(){
            return this.$wrapper.find('.sessionListItem.current');    
        },
        getUnread : function(){
            return this.$wrapper.find('.sessionListItem .unreadMsgCount').map( 
                function(){
                    return parseInt($(this).text()) || 0; 
                } 
            ).get().sum();    
        },
        getUnreadSC : function(){
            var count = 0;
            this.$wrapper.find('.sessionListItem .unreadMsgCount').map(function(){
                var unreadC = parseInt($(this).text()) || 0; 
                if(unreadC > 0){
                    count++;
                }
            });
            return count;    
        },
        /**
         * 删除指定的session item.  
         * @param {String} sid
         */
        deleteSession : function(sid){
            this.$wrapper.find('.sessionListItem[sid={0}]'.format(sid)).remove();            
            if(ChatPanel.isActiveChatPanel(sid)){
                page.contentCardLayout.showItem('dashboard');
            } 
        },
        addItem : function(data, isSelected){
            var _this = this;
            this.store.addItem(data);
            if(isSelected != false){
                (function(){
                    _this.$wrapper.find('.sessionListItem[sid={0}]'.format(data['id'])).trigger('click');    
                }).defer(0);
            }
        },        
        getSessionItem : function(sid){
            return this.$wrapper.find('.sessionListItem[sid={0}]'.format(sid));    
        },
        addOrderly : function($item){
            var lastdotime = parseInt($item.attr('lastdotime'));
            var $sessionListItems = this.$wrapper.find('.sessionListItem');
            if(!$sessionListItems.length){
                this.$wrapper.append($item);
                return this;
            } else {
                for(var i=0; i<$sessionListItems.length; i++){
                    var $cur = $($sessionListItems.get(i));
                    var nowTime = parseInt($cur.attr('lastdotime'));
                    if(lastdotime > nowTime){
                        $cur.before($item);
                        return this;
                    }
                }
            }
            this.$wrapper.append($item);
            return this;
        },
        updateItem : function(sid, fun){
            var teObj = page.chatGroupStore.getItem(sid);
            if(Type.isFunction(fun)){
                fun(teObj);
            }
            if(teObj && !Type.isEmptyObject(teObj)){
                sessionList.addItem(teObj, false);
            }
        },
        startSession : function(teid, mode, seq){
            sessionList.addItem(page.chatGroupStore.getItem(teid));
            
        },
        addSessionItem : function(teid){
            sessionList.addItem(page.chatGroupStore.getItem(teid), false);
        }
    });
})();